package com.myapplication.app;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.myapplication.app.bean.TryJsonUtil;

import java.io.File;

/**
 * Created by tukela on 2015/3/2.
 */
public class RegisterActivity extends Activity implements View.OnClickListener{
    String sex="1"; //1男 2女
    String  phone="";
    String  name="";
    String  account="";
    String  passwd="";
    private ImageView imageFemale;
    private EditText Textphone;
    private ImageView imageHeader;
    private ImageView imageMale;
    private ImageView imageShow;
    private ImageView imagePhoto;
    private ImageView imageCamera;
    private EditText TextName;
    private EditText TextAccount;
    private EditText TextPasswd;
    private EditText TextPasswd2;
    private Button btnLogin;
    private int REQUESTCODE=0x123;
    private int PHOTOCODE=0x1;
    private int CAMERACODE=0x2;
    private String passwd2="";
    private int FISHCODE=0x111;
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        mHandler=new Handler();
        init();
    }
    public void init(){
        imageFemale= (ImageView) findViewById(R.id.female);
        imageHeader= (ImageView) findViewById(R.id.header);
        imageMale= (ImageView) findViewById(R.id.male);
        Textphone= (EditText) findViewById(R.id.phone);
        TextName=(EditText) findViewById(R.id.name);
        imageShow= (ImageView) findViewById(R.id.showheader);
        imagePhoto= (ImageView) findViewById(R.id.photo);
        imageCamera= (ImageView) findViewById(R.id.camera);
        TextAccount=(EditText) findViewById(R.id.account);
        TextPasswd=(EditText) findViewById(R.id.passwd);
        TextPasswd2=(EditText) findViewById(R.id.passwd2);
        btnLogin= (Button) findViewById(R.id.login);
        imageFemale.setOnClickListener(this);
        imageHeader.setOnClickListener(this);
        imageMale.setOnClickListener(this);
        imageShow.setOnClickListener(this);
        imagePhoto.setOnClickListener(this);
        imageCamera.setOnClickListener(this);
        Textphone.setOnClickListener(this);
        TextName.setOnClickListener(this);
        TextAccount.setOnClickListener(this);
        TextPasswd.setOnClickListener(this);
        TextPasswd2.setOnClickListener(this);
        btnLogin.setOnClickListener(this);

    }
    public boolean checkRight(){
        phone=Textphone.getText().toString();
        name=TextName.getText().toString();
        account=TextAccount.getText().toString();
        passwd=TextPasswd.getText().toString();
        passwd2=TextPasswd2.getText().toString();
        if(phone.equals("")||null==phone)
        {
            showMessage("手机号不能为空");
            return false;
        }
        else if(name.equals("")||null ==name)
        {
            showMessage("昵称不能为空");
            return false;
        }
        else if(account.equals("")||null==account)
        {
            showMessage("账户不能为空");
            return false;
        }
        else if(passwd.equals("")||null==passwd)
        {
            showMessage("密码不能为空");
            return false;
        }
        else  if(passwd2.equals("")||null==passwd2)
        {
            showMessage("确认密码不能为空");
            return false;
        }
        else  if(!passwd2.equals(passwd))
        {
            showMessage("密码不一致");
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.female://女
                sex="2";
                imageHeader.setBackgroundResource(R.drawable.ic_launcher);
                break;
            case R.id.male://男
                sex="1";
                imageHeader.setBackgroundResource(R.drawable.ic_launcher);
                break;
            case R.id.photo:
//                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//                intent.addCategory(Intent.CATEGORY_OPENABLE);
//                intent.setType("image/*");
//                intent.putExtra("crop", "true");
//                intent.putExtra("aspectX",1);
//                intent.putExtra("aspectY",1);
//                intent.putExtra("outputX", 80);
//                intent.putExtra("outputY", 80);
//                intent.putExtra("return-data",true);
//                startActivityForResult(intent, PHOTOCODE);

                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, PHOTOCODE);
                break;
            case R.id.camera:
                Intent intent2 = new Intent("android.media.action.IMAGE_CAPTURE");
                intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "camera.jpg")));
                intent2.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
                startActivityForResult(intent2,CAMERACODE);
                break;
            case R.id.login:
                checkRight();
                loadDate();

                break;
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERACODE && resultCode == Activity.RESULT_OK) {
           Bitmap bitmap= BitmapFactory.decodeFile(new File(
                    Environment.getExternalStorageDirectory(), "camera.jpg")
                    .getAbsolutePath());
            bitmap=TryJsonUtil.getRoundedCornerBitmap(bitmap,2);
            imageShow.setImageBitmap(bitmap);
//            imageShow.setBackground(Drawable.createFromPath(new File(
//                    Environment.getExternalStorageDirectory(), "camera.jpg")
//                    .getAbsolutePath()));
//            imageShow.setImageDrawable(Drawable.createFromPath(new File(
//                    Environment.getExternalStorageDirectory(), "camera.jpg")
//                    .getAbsolutePath()));
        }else if (requestCode == PHOTOCODE && resultCode ==Activity.RESULT_OK) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            Bitmap bitmap= BitmapFactory.decodeFile(picturePath);
            bitmap=TryJsonUtil.getRoundedCornerBitmap(bitmap,2);
            imageShow.setImageBitmap(bitmap);
//            imageShow.setImageBitmap(BitmapFactory.decodeFile(picturePath));
//            Bitmap cameraBitmap = (Bitmap) data.getExtras().get("data");
//            imageShow.setImageDrawable(new BitmapDrawable(cameraBitmap));
        }else if (requestCode == FISHCODE && resultCode ==Activity.RESULT_OK) {
            this.setResult(RESULT_OK);//通知login结束
            //结束本Activity
            finish();
        }
    }
    public void showMessage(String str){
        Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
    }

    public void loadDate(){

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                loading();
            }
        }, 0);
    }
    private void loading(){
        RequestParams params = new RequestParams();
        params.addBodyParameter("username", name);
        params.addBodyParameter("pass", passwd);
        params.addBodyParameter("mobile", phone);
        params.addBodyParameter("sex", sex);

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, MyApp.BSURL
                ,
                params,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        //  testTextView.setText("reply: " + responseInfo.result);
                        String str= TryJsonUtil.isJsonRight(responseInfo.result);
                        if (str.contains("注册成功"))
                        {
                            Intent intent3 = new Intent(RegisterActivity.this,Register2Activity.class);
                            startActivityForResult(intent3, FISHCODE);
                        }else {
                            showMessage("注册失败，请重试");
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        showMessage("注册失败，请重试");
                        Intent intent3 = new Intent(RegisterActivity.this,Register2Activity.class);
                        startActivityForResult(intent3, FISHCODE);
                    }
                });

    }
}
